#!/usr/bin/env python3
#
# Copyright (c) 2010 - 2025, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# We kindly request you to use one or more of the following phrases to refer to
# foxBMS in your hardware, software, documentation or advertising materials:
#
# - "This product uses parts of foxBMS®"
# - "This product includes parts of foxBMS®"
# - "This product is derived from foxBMS®"

"""Host and SPA build of the unit test suite"""

# pylint: disable=too-many-locals

import collections
import hashlib
import os
from pathlib import Path

from waflib import Build, Context, Logs
from waflib.Build import BuildContext, CleanContext
from waflib.Configure import ConfigurationContext
from waflib.Node import Node
from waflib.Options import OptionsContext
from waflib.Tools import waf_unit_test
from waflib.Utils import unversioned_sys_platform


def sorting_error(unit_under_test, test_case, setup, key):
    """Display an error message"""
    err_msg = (
        f"File under test: '{unit_under_test}'\n"
        f"  Test case: '{test_case}'\n\n"
        f"  key: '{key}': should be:"
        f"  {sorted(setup[key])}\n\n"
    )
    return err_msg


def get_bld(self: Node):
    """Based on the implementation get_bld():
    https://gitlab.com/ita1024/waf/-/blob/ad7b733fc60852f77eff200b79e8b6f9562494d2/waflib/Node.py#L783-807
    but we do not need the '__root__' feature
    """
    cur = self
    lst = []
    while cur.parent:
        if cur is self.ctx.bldnode:
            return self
        if cur is self.ctx.srcnode:
            lst.reverse()
            return self.ctx.bldnode.make_node(lst)
        lst.append(cur.name)
        cur = cur.parent
    lst.reverse()
    lst = list(
        filter(("..").__ne__, str(self.path_from(self.ctx.bldnode)).split(os.sep))
    )
    return self.ctx.bldnode.make_node(lst)


Node.get_bld = get_bld

COMMON_CFLAGS = [
    "-g",
    "-DGNU_COMPILER",
    "-DUNITY_UNIT_TEST",
    "-DUNITY_INCLUDE_EXEC_TIME",
    "-DUNITY_USE_COMMAND_LINE_ARGS",
    "-std=c11",
    "-Wextra",
    "-Wall",
    "-pedantic",
    "-include",
    "test_ignore_list.h",
]

if unversioned_sys_platform() != "win32":
    COMMON_CFLAGS.append("-D_POSIX_C_SOURCE=200809L")  # see project.yml

VARIANTS = ["host", "axivion"]


for x in VARIANTS:
    for y in (BuildContext, CleanContext):
        NAME = y.__name__.replace("Context", "").lower()

        class TMP(y):  # pylint: disable=missing-class-docstring
            __doc__ = f"""{NAME} command for the '{x}' variant"""

            cmd = NAME + "_" + x
            variant = x


def options(opt: OptionsContext):
    """Available build options"""
    opt.top = "."
    opt.load("compiler_c")
    opt.load("waf_unit_test")

    # remove unsupported options
    all_contexts = Context.classes
    all_contexts.remove(Build.InstallContext)
    all_contexts.remove(Build.UninstallContext)
    for k in (
        "--targets",
        "--distcheck-args",
        "--out",
        "--prefix",
        "--destdir",
        "--bindir",
        "--libdir",
        "--msvc_version",
        "--msvc_targets",
        "--no-msvc-lazy",
        "--force",
        "--testcmd",
        "--check-c-compiler",
    ):
        option = opt.parser.get_option(k)
        if option:
            opt.parser.remove_option(k)

    remaining_options = []
    for i in opt.parser.option_groups:
        if i.title not in (
            "Installation and uninstallation options",
            "Configuration options",
        ):
            remaining_options.append(i)
    opt.parser.option_groups = remaining_options


def configure(cnf: ConfigurationContext):
    """configures gcc for the host build (gcc) and cafeCC for the SPA build."""
    expected = (Path(cnf.path.abspath()) / "axivion").as_posix()
    actual = Path(os.getenv("BAUHAUS_CONFIG", "")).as_posix()

    if expected != actual:
        cnf.fatal(f"Environment variable 'BAUHAUS_CONFIG' must be set to {expected}.")

    # copy environments
    cnf.setenv("host")  # gcc (native)
    cnf.setenv("axivion")  # cafeCC (SPA)

    # host
    cnf.setenv("host")
    cnf.load("python")

    cnf.define("FAS_ASSERT_LEVEL", 2)
    cnf.define("FOXBMS_USES_FREERTOS", 1)
    cnf.env.append_unique("CFLAGS", COMMON_CFLAGS)
    cnf.env.append_value("INCLUDES", [cnf.path.find_node("support").abspath()])

    cnf.options.check_c_compiler = "gcc"
    cnf.load("compiler_c")
    cnf.find_program("ceedling", mandatory=False)

    if cnf.env.CC_NAME.lower() == "gcc":
        cnf.load("waf_unit_test")  # test are only executable for gcc-builds
        cnf.check_cc(lib="m", uselib_store="M")  # see project.yml

    fragment = "#include <stdint.h>\n\nint sum(int a, int b){\n    return (a + b);}\n"
    cnf.check(features="c cstlib", fragment=fragment)
    fragment = "int main() {\n    return 0;\n}"
    cnf.check(features="c cprogram", fragment=fragment)

    # Axivion
    cnf.setenv("axivion")
    cnf.load("python")

    cnf.define("FAS_ASSERT_LEVEL", 2)
    cnf.define("FOXBMS_USES_FREERTOS", 1)
    cnf.env.append_unique("CFLAGS", COMMON_CFLAGS)
    cnf.env.append_value("INCLUDES", [cnf.path.find_node("support").abspath()])

    cnf.options.check_c_compiler = "gcc"
    cnf.load("compiler_c")
    cnf.find_program("ceedling", mandatory=False)

    try:
        cnf.find_program("axivion_config", var="AXIVION_CONFIG")
        cnf.find_program("cafecc", var="AXIVION_CC")
        cnf.find_program("irdump", var="AXIVION_IR_DUMP")
    except cnf.errors.ConfigurationError as err:
        Logs.warn(
            "Could not configure Axivion build, so it will not be "
            f"available. Error:\n\n{err}\n"
        )
        return
    cnf.env.append_unique("AXIVION_IR_DUMP_ARGS", "-m")
    cnf.env.append_unique("LINKFLAGS", ["-echo", "-larg", "--show_plan"])

    cnf.env.CC = cnf.env.AXIVION_CC
    cnf.env.LINK_CC = cnf.env.AXIVION_CC

    fragment = "#include <stdint.h>\n\nint sum(int a, int b){\n    return (a + b);}\n"
    cnf.check(features="c cstlib", fragment=fragment)
    fragment = "int main() {\n    return 0;\n}"
    cnf.check(features="c cprogram", fragment=fragment)


# pylint: disable=too-many-branches,too-many-statements
def build(bld: BuildContext):
    """High level definition of the build details"""
    if not bld.variant:
        supported_cmds = ", ".join([f"{bld.cmd}_{i}" for i in VARIANTS]).strip()
        bld.fatal(f"supported build commands: {supported_cmds}")

    if bld.variant == "axivion" and not bld.env.AXIVION_IR_DUMP:
        bld.fatal(
            "Axivion support was not successfully configured, "
            "therefore it is not available."
        )

    bld.env = bld.all_envs[bld.variant]

    # when cleaning(!), no further processing of needed
    if not bld.cmd.startswith("build"):
        return

    str_root = os.path.join(bld.path.abspath(), "..", "..")
    root = bld.root.find_dir(str_root)
    ceedling_dir: Node = bld.root.find_node(bld.env.CEEDLING[0]).parent.parent
    ceedling_vendor_dir = ceedling_dir.find_dir("gems/ceedling-1.0.1/vendor")
    # dirs
    inc_unity = ceedling_vendor_dir.find_dir("unity/src")
    inc_cmock = ceedling_vendor_dir.find_dir("cmock/src")
    inc_c_exception = ceedling_vendor_dir.find_dir("c_exception/lib")
    # to-be-compiled-sources
    unity_c = bld.path.find_or_declare("unity.c")
    cmock_c = bld.path.find_or_declare("cmock.c")
    cexception_c = bld.path.find_or_declare("CException.c")
    # target names
    unity = "unity"
    cmock = "cmock"
    c_exception = "CException"

    bld(
        features="subst",
        source=inc_unity.find_node("unity.c"),
        target=unity_c,
        is_copy=True,
    )
    bld(
        features="subst",
        source=inc_cmock.find_node("cmock.c"),
        target=cmock_c,
        is_copy=True,
    )
    bld(
        features="subst",
        source=inc_c_exception.find_node("CException.c"),
        target=cexception_c,
        is_copy=True,
    )
    bld.add_group()

    bld.objects(source=[unity_c], includes=[inc_unity], target=unity)
    bld.objects(source=[cmock_c], includes=[inc_cmock, inc_unity], target=cmock)
    bld.objects(source=[cexception_c], includes=[inc_c_exception], target=c_exception)

    units_under_test_file: Node = bld.path.find_node("build.json")
    units_under_test: dict = units_under_test_file.read_json()
    err = 0
    listed_files = []
    for k, v in units_under_test.items():
        # maybe the unit test cannot be performed on the platform the tests
        # are built, so just exclude the test and print a warning

        if skip_platforms := units_under_test.get("skip", ""):
            if unversioned_sys_platform() in skip_platforms:
                Logs.warn(f"Test '{k}' is not available on this platform.")
                continue
        if not root.find_node(k):
            err += 1
            Logs.error(f"Could not find source file '{k}'.")
        else:
            listed_files.append(k)

    if err:
        bld.fatal("Missing source files.")
    # check that everything is well sorted

    for k, v in units_under_test.items():
        for i, test in enumerate(v):
            if test.get("defines", []) != sorted(test.get("defines", [])):
                bld.fatal(sorting_error(k, i, test, "defines"))
            if test.get("include", []) != sorted(test.get("include", [])):
                bld.fatal(sorting_error(k, i, test, "include"))
            if test.get("sources", []) != sorted(test.get("sources", [])):
                bld.fatal(sorting_error(k, i, test, "sources"))
    files = []
    for i in root.ant_glob(
        "src/app/**/*.c src/opt/cells/config/*.c",
        excl=[
            "**/vendor/**",
            "**/fs8x_driver/**",  # vendored SBC files
        ]
        + [str(root.find_node("src/app/driver/afe/maxim/common/mxm_register_map.h"))],
    ):
        files.append(Path(i.path_from(root)).as_posix())
    if diff := set(files) - set(listed_files):
        bld.fatal(
            "The files in the sources tree do not match the files defined "
            f"in the build configuration '{units_under_test_file.relpath()}':\n{', '.join(diff)}"
        )

    # all test files shall be included somewhere in the source tree, otherwise
    # the test file is not compiled and therefore not tested
    relevant_test_files = []

    for i in root.ant_glob(
        "tests/unit/app/**/test_*.c",
        "tests/unit/opt/**/test_*.c",
        excl=[
            # these are the dummy files, see
            # tests/unit/app/driver/afe/adi/common/ades183x/README.md
            "tests/unit/app/driver/afe/adi/common/ades183x/**",
            "tests/unit/support/**",
        ],
        quiet=True,
    ):
        relevant_test_files.append(Path(i.path_from(root)).as_posix())

    for i in relevant_test_files:
        found = False
        for k, tests in units_under_test.items():
            for test in tests:
                if i in test.get("sources", []):
                    found = True
                    break
        if not found:
            txt = (Path(root.abspath()) / Path(i)).read_text(encoding="utf-8")
            if "/* this is a dummy test file */" not in txt:
                bld.fatal(f"Test file '{i}' is not listed in any build instruction.")
    test_runners = []
    test_implementation_files = []
    for i, (k, v) in enumerate(units_under_test.items()):
        for test in v:
            # check if the test file shall be ignored or is not available on
            # the used platform
            if test.get("ignore", False):
                if not test.get("_comment", ""):
                    bld.fatal(
                        "Ignored test files require an explanation "
                        f"comment (test file {k})."
                    )
                continue
            if skip_platforms := test.get("skip", ""):
                if unversioned_sys_platform() in skip_platforms:
                    Logs.warn(f"Test '{k}' is not available on this platform.")
                    continue

            test_base_name = k.rsplit("/", maxsplit=1)
            test_name = ""
            test_runner = ""
            unit_under_test = f"{test_base_name[1].rsplit('.', maxsplit=1)[0]}"
            expected_unit_under_test_infix = (
                test.get("runner-alias", None) or unit_under_test
            )
            expected_test_name = f"test_{expected_unit_under_test_infix}.c"
            expected_runner_name = f"test_{expected_unit_under_test_infix}_runner.c"
            for source in test["sources"]:
                if source.endswith(f"/{expected_runner_name}"):
                    test_runners.append(source)
                    if not test_runner:
                        test_runner = source
                if source.endswith(f"/{expected_test_name}"):
                    test_implementation_files.append(source)
                    if not test_name:
                        test_name = source
            if not test_runner:
                bld.fatal(
                    f"DUT: {k}: Could not find expected runner file "
                    f"'{expected_runner_name}' in sources list"
                )
            if not test_name:
                bld.fatal(
                    f"DUT: {k}: Could not find expected test file "
                    f"'{expected_test_name}' in sources list"
                )
            # to avoid recompilations, but still give every test binary an
            # unique name, we hash the filename into a integer
            run_id = int.from_bytes(hashlib.md5(test_runner.encode()).digest(), "big")
            test_runner_out = f"{test_runner}.{run_id}.exe"
            sources = []
            for source in test["sources"]:
                found = root.find_node(source)
                if not found:
                    bld.fatal(
                        f"Could not find source '{source}' defined for '{test_runner}'."
                    )
                sources.append(found)
            defines = test.get("defines", [])
            cflags = test.get("flags", [])
            bld(
                features="c",
                source=sources,
                defines=defines,
                cflags=cflags,
                use=[unity, cmock, c_exception],
                includes=[inc_c_exception, inc_cmock, inc_unity]
                + [root.find_dir(i) for i in test["include"]],
                target=f"objects-{run_id}",
                idx=run_id,
            )
            features = "c cprogram"
            if bld.variant == "host":
                features += " test"
            bld(
                features=features,
                use=[f"objects-{run_id}", unity, cmock, c_exception] + ["M"],
                includes=[inc_c_exception, inc_cmock, inc_unity]
                + [root.find_dir(i) for i in test["include"]],
                target=bld.path.find_or_declare(test_runner_out),
                idx=run_id,
            )

    if bld.variant == "host":
        bld.add_post_fun(waf_unit_test.summary)

    duplicate_test_runners = [
        item for item, count in collections.Counter(test_runners).items() if count > 1
    ]
    if duplicate_test_runners:
        bld.fatal(f"Some runners are listed more than once:\n{duplicate_test_runners}")

    duplicate_test_implementation_files = [
        item
        for item, count in collections.Counter(test_implementation_files).items()
        if count > 1
    ]
    if duplicate_test_implementation_files:
        bld.fatal(
            f"Some runners are listed more than once:\n{duplicate_test_implementation_files}"
        )
